<template>
<el-drawer :title="drawer.title" :visible.sync="drawer.visible" direction="rtl">
    <el-form ref="roleForm" label-width="80px" label-position="left" class="role-form">
        <el-form-item label="角色列表">
            <el-checkbox-group v-model="selectedRoleList">
                <el-checkbox v-for="(item, index) in allRoleList" :key="index" :label="item.id" :name="item.id + ''">{{ item.title }}</el-checkbox>
            </el-checkbox-group>
        </el-form-item>

        <el-form-item>
            <el-button type="primary" @click="submit">保存</el-button>
        </el-form-item>
    </el-form>
</el-drawer>
</template>

<script>
import {
    bindUserRoleApi,
    getUserRoleApi
} from "@/api/ucenter/user";
import {
    getRoleListApi
} from "@/api/auth/role";

export default {
    name: "setRole",
    data() {
        return {
            drawer: {
                title: "角色授权",
                visible: false,
            },
            allRoleList: [], // 所有角色
            selectedRoleList: [], // 已绑定的角色
            user_id: "",
            // 所有角色列表
            
        };
    },
    methods: {
        // 显示
        showDrawer(options) {
            this.user_id = options.id;
            // 显示当前
            this.drawer.visible = true;
            // 获取所有角色列表
            this.getRoleList();
            // 获取用户已绑定角色
            this.getUserRole();
        },

        // 获取所有角色列表
        getRoleList() {
            getRoleListApi().then((res) => {
                if (res.code == 200) {
                    this.allRoleList = res.data.list;
                }
            });
        },

        // 获取用户已绑定角色
        getUserRole() {
            let params = {
                user_id: this.user_id,
            };

            getUserRoleApi(params).then((res) => {
                if (res.code == 200) {
                    this.selectedRoleList = res.data.roles;
                }
            });
        },

        // 提交
        submit() {
            let params = {
                user_id: this.user_id,
                role: this.selectedRoleList,
            };
            bindUserRoleApi(params).then((res) => {
                if (res.code == 200) {
                    this.$message.success(res.msg);
                    this.drawer.visible = false;
                    this.$emit("getTableData", {})
                } else {
                    this.$message.warning(res.msg);
                }
            });
        },
    },
};
</script>

<style lang="scss" scoped>
.role-form {
    padding: 0 32px;

    .el-checkbox {
        width: 6rem;
        margin-right: 15px;
    }
}
</style>
